#!/bin/bash

echo "🔧 快速修复VNC连接问题..."
echo

# 检查容器状态
echo "1. 检查容器状态..."
if docker ps | grep -q ubuntu-desktop-lightweight; then
    echo "✅ 容器正在运行"
else
    echo "❌ 容器未运行，请先启动容器"
    exit 1
fi

echo
echo "2. 进入容器安装VNC服务器..."
docker exec -it ubuntu-desktop-lightweight bash -c "
echo '正在安装VNC服务器...'
apt-get update
apt-get install -y tightvncserver x11vnc
echo 'VNC服务器安装完成'
"

echo
echo "3. 启动VNC服务器..."
docker exec -it ubuntu-desktop-lightweight bash -c "
echo '启动VNC服务器...'
export DISPLAY=:99
x11vnc -display :99 -forever -nopw -listen 0.0.0.0 -xkb -ncache 10 -ncache_cr -description 'Ubuntu Desktop' &
echo 'VNC服务器已启动'
"

echo
echo "4. 验证VNC服务..."
sleep 3
if docker exec ubuntu-desktop-lightweight pgrep -x x11vnc > /dev/null; then
    echo "✅ VNC服务器运行正常"
else
    echo "❌ VNC服务器启动失败"
fi

echo
echo "5. 检查端口监听..."
docker exec ubuntu-desktop-lightweight netstat -tlnp | grep 5900 || echo "端口5900未监听"

echo
echo "=================================="
echo "VNC修复完成！"
echo "=================================="
echo
echo "现在可以尝试连接VNC："
echo "  - 地址: localhost:5901"
echo "  - 无需密码"
echo
echo "如果仍然无法连接，请尝试："
echo "  1. 重启容器: docker-compose -f docker-compose.lightweight.yml restart"
echo "  2. 重新构建镜像: docker-compose -f docker-compose.lightweight.yml build --no-cache"
echo "  3. 使用SSH访问: ssh -p 2223 ubuntu@localhost"
echo 